import glob
import os
import shutil

word = ""
cnt=0
for i in glob.glob("./*"):
    i = i[2:]

    boolean = (
        "py" not in i
        and "Server" not in i
        and "." not in i
        and "download" not in i
        and "api" not in i
        and "json" not in i
        and os.path.isdir(i)
    )
    if boolean:
        cnt+=1

# --------------------删除迁徙文件
        if os.path.exists(f"{i}/migrations"):
            for j in glob.glob(f"{i}/migrations/0*"):
                os.remove(j)
            print(i)

# --------------------配置view.py urls.py serializer.py
        if '_' in i:
            c=''.join( [j.capitalize() for  j in  i.split('_')])
        else:
            c=i.capitalize()

        with open(f"{i}/views.py", "w", encoding="utf-8") as f:
            f.write(
f"""
from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.response import Response

from .models import {c}
from .serializer import {c}Serializer


class {c}ViewSet(viewsets.ModelViewSet):
    queryset = {c}.objects.all()
    serializer_class = {c}Serializer

    def perform_create(self, serializer):
        serializer.save()

    @action(detail=False, methods=["get"], url_path="api/(?P<value>[^/.]+)")
    def select(self, request, value):
        # 获取 URL 参数
        filter_dict = dict(self.request.query_params.items())
        list_value = self.kwargs.get("value").split(',')
        queryset = {c}.objects.filter(**filter_dict).values(*list_value, "id")
        return Response( """+ '{"results": queryset})' +  """

"""
)

        with open(f"{i}/urls.py", "w", encoding="utf-8") as f:
            f.write(
f"""
from django.urls import path, include
from rest_framework.routers import DefaultRouter

from .views import {c}ViewSet


router = DefaultRouter()
router.register('viewsets', {c}ViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api/<str:value>', {c}ViewSet.as_view( """+ "{'get': 'select'}" +  """ )),
]

"""
)
        with open(f"{i}/serializer.py", "w", encoding="utf-8") as f:
            f.write(
f"""
from rest_framework import serializers
from .models import {c}


class {c}Serializer(serializers.ModelSerializer):
    class Meta:
        model = {c}
        fields = '__all__'

"""
)

print(cnt)